package com.dong.algorithm.novice.search;

import com.dong.algorithm.novice.introduction.Arg04_ResultValidatorUse;

import java.util.Arrays;

/**
 * 二分查找
 * 有序数组中找到<=num最右的位置
 *
 * @author by jiweidong on 2021/11/22.
 */
public class Arg03_BinarySearchMostRightNoGreaterNum {

    // arr 保证有序
    public static int binarySearchMostRightNoGreaterNum (int[] arr, int num) {
        if (arr == null || arr.length == 0) {
            return -1;
        }

        int L = 0;
        int R = arr.length - 1;
        int ans = -1;
        while (L <= R) {
            int mid = (L + R) / 2;
            if (arr[mid] <= num) {
                ans = mid;
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }

        return ans;
    }

    public static void main(String[] args) {

        int testTime = 500000;
        int maxSize = 10;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr = Arg04_ResultValidatorUse.generateRandomArray(maxSize, maxValue);
            Arrays.sort(arr);
            int value = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
            if (test(arr, value) != binarySearchMostRightNoGreaterNum(arr, value)) {
                System.out.println("出错了！");
                succeed = false;
                break;
            }
        }
        System.out.println(succeed ? "Nice!" : "Fucking fucked!");
    }

    // for test
    // 对数器
    public static int test(int[] sortedArr, int num) {
        for (int i = sortedArr.length - 1; i >= 0; i--) {
            if (sortedArr[i] <= num) {
                return i;
            }
        }
        return -1;
    }

}
